import Vue from 'vue'
import VueRouter from 'vue-router'
import routerList from './routeList'

import baseInfo from '@/utils/config'
import { getTokenInfo, getUserInfo } from '../utils/publicFun'

Vue.use(VueRouter)

// 解决push当前路由的报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes: routerList,
  mode: 'history'
})
const setTitle = (title) => {
  return `${title} - ${baseInfo.BASE_TITLE}`
}

const whiteList = baseInfo.ROTER_WHITE_LIST

const routerIntercept = () => {
  if (!baseInfo.ROUTER_INTERCEPT) return
  router.beforeEach((to, from, next) => {
    const token = getTokenInfo()

    const userInfo = getUserInfo()
    // 1.设置页面title
    document.title = setTitle(to.meta.title)
    // 2.判断是否登录
    if (token && userInfo) {
      if (to.path === '/login') {
        next({ path: '/' })
      }
      if (to.path === '/notfound' || to.path === '/') {
        next()
      } else {
        next()
      }
    } else {
      if (whiteList.includes(to.path)) {
        next()
      } else {
        next({ path: '/login' })
      }
    }
    // 3.判断是否在路由白名单内
    // 4.放行
    next()
  })
}
routerIntercept()

export default router
